// 商品参数
<template>
  <div class="class-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 头部提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 联级选择器 -->
      <div class="block">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader
          v-model="value"
          expand-trigger="hover"
          :options="catelist"
          :props="cateProps"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- 分页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnShow"
            size="mini"
            @click="dialogVisible = true"
            >添加参数</el-button
          >
          <!-- 表格 -->
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="{ row }">
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editDialog(row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="seleteParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnShow"
            size="mini"
            @click="dialogVisible = true"
            >静态属性</el-button
          >
          <!-- 表格 -->
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="{ row }">
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editDialog(row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="seleteParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="dialogVisible"
      width="50%"
      @close="showDialog"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改编辑对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editShowDialog"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsCateList } from "@/api/goods_cate";
import {
  getCateList,
  addParams,
  getQueryId,
  editParams,
  deleteParams,
} from "@/api/goods_params";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      // 选择器
      value: [], // 练级选择框双向绑定到的数组
      catelist: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeName: "many",
      manyTableData: [], //动态参数数据
      onlyTableData: [], //静态参数信息
      dialogVisible: false, //弹出层
      editDialogVisible: false, //编辑对话框
      addForm: {
        attr_name: "",
      }, //表单数据
      editForm: {},
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      }, //表单校验规则
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      }, //表单校验规则
    };
  },
  computed: {
    // 按钮的禁用
    isBtnShow() {
      return this.value.length !== 3 ? true : false;
    },
    cateId() {
      return this.value.length === 3 ? this.value[2] : null;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
  watch: {},
  created() {
    this.getGoodsCateList();
  },
  methods: {
    handleChange() {
      this.getParamsDate();
    },
    async getParamsDate() {
      if (this.value.length !== 3) {
        // 清空选择器的数据
        this.value = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      } else {
        const { data } = await getCateList({
          id: this.cateId,
          sel: this.activeName,
        });
        data.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          // 控制文本框的显示和隐藏
          item.inputVisible = false;
          // 文本框输入的值
          item.inputValue = "";
        });
        if (this.activeName === "many") {
          this.manyTableData = data.data;
        } else {
          this.onlyTableData = data.data;
        }
      }
    },
    // 获取商品分类数据
    async getGoodsCateList() {
      const { data } = await getGoodsCateList();
      this.catelist = data.data;
    },
    // tabs 栏切换
    handleClick() {
      console.log(this.activeName);
      this.getParamsDate();
    },
    // 关闭弹窗
    showDialog() {
      // this.dialogVisible = false
      this.$refs.addFormRef.resetFields();
    },
    editShowDialog() {
      this.$refs.editFormRef.resetFields();
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          const { data } = await addParams({
            id: this.cateId,
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          });
          console.log(data);
          if (data.meta.status !== 201)
            return this.$message.error("添加参数失败");
          this.$message.success("添加参数成功!");
          this.dialogVisible = false;
          this.getParamsDate();
        }
      });
    },
    // 修改对话框的编辑按钮
    async editDialog(id) {
      this.editDialogVisible = true;
      const { data } = await getQueryId(this.cateId, id, this.activeName);
      this.editForm = data.data;
    },
    // 修改参数
    async editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data } = await editParams(
          this.cateId,
          this.editForm.attr_id,
          this.editForm.attr_name,
          this.activeName
        );
        if (data.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("修改成功！");
        this.getParamsDate();
        this.editDialogVisible = false;
      });
    },
    // 删除
    async seleteParams(id) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteParams(this.cateId, id);
          this.getParamsDate();
          this.$message.success("删除成功！");
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      } else {
        row.attr_vals.push(row.inputValue.trim());
        console.log(row);
        row.inputVisible = false;
        row.inputValue = "";
        const { data: res } = await editParams(
          this.cateId,
          row.attr_id,
          row
        );
        if (res.meta.status !== 200) return this.$message.error("添加失败");
        this.$message.success("添加成功！");
      }
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除标签
    async handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      const { data: res } = await editParams(
        this.cateId,
        row.attr_id,
        row
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除失败");
    },
  },
};
</script>

<style scoped lang='sass'>
.class-container
  padding: 20px
  .box-card
    margin-top: 20px
    .el-alert
      margin-bottom: 20px

    .el-table--border
      margin-top: 20px
  .el-tag + .el-tag
    margin-left: 10px

  .button-new-tag
    margin-left: 10px
    height: 32px
    line-height: 30px
    padding-top: 0
    padding-bottom: 0

  .input-new-tag
    width: 90px
    margin-left: 10px
    vertical-align: bottom
</style>